#!/bin/bash

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
INSTALL_DIR="/opt/cmdb-agent"
CONFIG_DIR="${INSTALL_DIR}/etc"
SERVICE_NAME="cmdb-agent"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

function log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

function log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

function log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

function log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

function check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用 root 权限运行此脚本"
        exit 1
    fi
}

function confirm_uninstall() {
    log_warn "即将卸载 CMDB Agent 服务"
    echo -e "${YELLOW}此操作将:${NC}"
    echo "  1. 停止并禁用 ${SERVICE_NAME} 服务"
    echo "  2. 删除 systemd 服务文件"
    echo "  3. 删除安装目录 ${INSTALL_DIR}"
    echo ""
    read -p "确认卸载？(yes/no): " -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
        log_info "取消卸载"
        exit 0
    fi
}

function stop_and_disable_service() {
    log_step "停止服务..."
    
    if systemctl is-active --quiet ${SERVICE_NAME} 2>/dev/null; then
        log_info "停止 ${SERVICE_NAME} 服务..."
        systemctl stop ${SERVICE_NAME} || log_warn "停止服务失败"
    else
        log_info "服务未运行"
    fi
    
    if systemctl is-enabled --quiet ${SERVICE_NAME} 2>/dev/null; then
        log_info "禁用 ${SERVICE_NAME} 服务..."
        systemctl disable ${SERVICE_NAME} || log_warn "禁用服务失败"
    else
        log_info "服务未启用"
    fi
}

function remove_service_file() {
    log_step "删除 systemd 服务文件..."
    
    if [ -f "${SERVICE_FILE}" ]; then
        rm -f "${SERVICE_FILE}"
        log_info "已删除服务文件: ${SERVICE_FILE}"
        
        # 重新加载 systemd
        systemctl daemon-reload
        systemctl reset-failed 2>/dev/null || true
    else
        log_info "服务文件不存在，跳过"
    fi
}

function remove_install_dir() {
    log_step "删除安装目录..."
    
    if [ -d "${INSTALL_DIR}" ]; then
        # 备份配置文件（可选）
        if [ -f "${CONFIG_DIR}/config.yml" ]; then
            BACKUP_FILE="/tmp/cmdb-agent-config-backup-$(date +%Y%m%d%H%M%S).yml"
            cp "${CONFIG_DIR}/config.yml" "${BACKUP_FILE}"
            log_info "配置文件已备份至: ${BACKUP_FILE}"
        fi
        
        rm -rf "${INSTALL_DIR}"
        log_info "已删除安装目录: ${INSTALL_DIR}"
    else
        log_info "安装目录不存在，跳过"
    fi
}

function check_remaining_files() {
    log_step "检查残留文件..."
    
    local remaining=0
    
    if [ -f "${SERVICE_FILE}" ]; then
        log_warn "残留文件: ${SERVICE_FILE}"
        remaining=1
    fi
    
    if [ -d "${INSTALL_DIR}" ]; then
        log_warn "残留目录: ${INSTALL_DIR}"
        remaining=1
    fi
    
    if [ $remaining -eq 0 ]; then
        log_info "未发现残留文件"
    fi
}

function show_summary() {
    echo ""
    log_step "卸载完成！"
    echo ""
    echo -e "${GREEN}✓${NC} 服务已停止并禁用"
    echo -e "${GREEN}✓${NC} systemd 服务文件已删除"
    echo -e "${GREEN}✓${NC} 安装目录已删除"
    echo ""
    
    if [ -f "/tmp/cmdb-agent-config-backup-"*.yml 2>/dev/null ]; then
        echo -e "${BLUE}提示:${NC} 配置文件已备份至 /tmp/ 目录"
        echo ""
    fi
    
    log_info "CMDB Agent 已完全卸载"
}

function main() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}   CMDB Agent 卸载脚本${NC}"
    echo -e "${BLUE}================================${NC}"
    echo ""
    
    check_root
    confirm_uninstall
    stop_and_disable_service
    remove_service_file
    remove_install_dir
    check_remaining_files
    show_summary
}

main
